package com.example.a28796.beautiful.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a28796.beautiful.BeautyWebViewActivity;
import com.example.a28796.beautiful.MoreActivity;
import com.example.a28796.beautiful.R;
import com.example.a28796.beautiful.config.NetConfig;
import com.example.a28796.beautiful.zhangyuqiadapter.BeautyListAdapter;
import com.example.a28796.beautiful.zhangyuqiadapter.BeautyPagerAdapter;
import com.example.a28796.beautiful.zhangyuqiadapter.BeautyRecyAdapter;
import com.example.a28796.beautiful.zhangyuqibean.BeautyLocalBean;
import com.example.a28796.beautiful.zhangyuqibean.BeautyPagerBean;
import com.example.a28796.beautiful.zhangyuqibean.BeautyYouLikeBean;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by 28796 on 2016/8/29.
 */
public class FragmentBeautyBuy extends Fragment {
    private ListView mListView;
    private ViewPager mViewPager;
    private PagerAdapter mAdapter;
    private List<ImageView> images;
    private List<BeautyPagerBean.ObjBean.AdsBean> mData;
    private LinearLayout mLayout, mBtnListLayout1, mBtnListLayout2, mBtnListLayout3;
    private RecyclerView mRecyclerView;
    private GridLayoutManager mLayoutManager;
    private LinearLayout point_ll;
    private RecyclerView.Adapter recycyleAdapter;
    private List<BeautyYouLikeBean.ObjBean.ListDataBean> youLike;
    private List<BeautyLocalBean.ObjBean.ListDataBean> local;
    private BaseAdapter adapter;
    private int previous = 0;
    private boolean isrunning = false;
    private Handler handler;
    private TextView mTextView, mTextViewPop;

    ArrayList<String> mainMenuItems = new ArrayList<>(Arrays.asList("全国", "北京", "重庆", "福建", "广东", "海南", "河北", "黑龙江", "河南", "湖北"
            , "湖南"
    ));
    String[][] sub_main_menuArr = new String[][]{{"北京"}, {"重庆"}, {"福建省", "福州"}, {"广东省", "广州", "东莞", "佛山", "深圳"}, {"海南省", "海口", "三亚"}
            , {"河北省", "石家庄"}, {"黑龙江省", "哈尔滨"}, {"河南省", "郑州"}, {"湖北省", "荆州", "武汉", "咸宁", "宜昌"}
            , {"湖南省", "长沙"}
    };
    ArrayList<String> subMenueList = new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_beautybuy, null);
        initView(view);
        initData();
        setData();
        setListener();
        getSelect();
        handler.sendEmptyMessageDelayed(0, 3000);
        return view;
    }

    private void setListener() {
        mTextViewPop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMainMenu(v);
            }
        });
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), MoreActivity.class));
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int newposition = position % images.size();
                if (images.size() != 0) {
                    point_ll.getChildAt(newposition).setEnabled(true);
                    point_ll.getChildAt(previous).setEnabled(false);
                    previous = newposition;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void getSelect() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                if (!isrunning) {
                    sendEmptyMessageDelayed(0, 3000);
                }

            }
        };
    }

    @Override
    public void onDestroy() {
        isrunning = true;
        super.onDestroy();
    }

    private void setData() {
        mViewPager.setAdapter(mAdapter);
        mRecyclerView.setAdapter(recycyleAdapter);
        mListView.setAdapter(adapter);
        int currentitem = Integer.MAX_VALUE / 2;
        mViewPager.setCurrentItem(currentitem);
    }

    private void initData() {
        images = new ArrayList<>();
        mAdapter = new BeautyPagerAdapter(images);
        youLike = new ArrayList<>();
        local = new ArrayList<>();
        adapter = new BeautyListAdapter(getActivity(), youLike, local);
        mData = new ArrayList<>();
        recycyleAdapter = new BeautyRecyAdapter(getActivity(), mData);
        x.http().get(new RequestParams(NetConfig.BEAUTYBUY_UP), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                BeautyPagerBean beautyPagerBean = gson.fromJson(result, BeautyPagerBean.class);
                List<BeautyPagerBean.ObjBean.AdsBean> ads = beautyPagerBean.getObj().getAds();
                View view = null;
                for (int i = 0; i < ads.size(); i++) {
                    mData.add(ads.get(i));
                }
                recycyleAdapter.notifyDataSetChanged();

                final List<BeautyPagerBean.ObjBean.CarouselsBean> carousels = beautyPagerBean.getObj().getCarousels();
                for (int i = 0; i < carousels.size(); i++) {
                    ImageView imageview = new ImageView(getActivity());
                    imageview.setScaleType(ImageView.ScaleType.FIT_XY);

                    Picasso.with(getActivity()).load(carousels.get(i).getCover().getUrl()).into(imageview);
                    final int finalI = i;
                    imageview.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String url = carousels.get(finalI).getUrl();
                            Intent intent = new Intent(getActivity(), BeautyWebViewActivity.class);
                            intent.putExtra("url", url);
                            startActivity(intent);
                        }
                    });
                    images.add(imageview);
                    view = new View(getActivity());
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(5, 5);
                    layoutParams.leftMargin = 15;
                    view.setLayoutParams(layoutParams);
                    view.setEnabled(false);
                    view.setBackgroundResource(R.drawable.point_seclect);
                    point_ll.addView(view);
                }
                point_ll.getChildAt(0).setEnabled(true);
                mAdapter.notifyDataSetChanged();


                final List<BeautyPagerBean.ObjBean.TopicsBean> topics = beautyPagerBean.getObj().getTopics();
                for (int i = 0; i < topics.size(); i++) {
                    String title = topics.get(i).getTitle();
                    final String url = topics.get(i).getCover().getUrl();

                    View scrollItem = View.inflate(getActivity(), R.layout.item_scroll_beauty, null);
                    TextView textViewTitle = (TextView) scrollItem.findViewById(R.id.tv_scroll_title);
                    textViewTitle.setText(title);
                    ImageView imageViewShow = (ImageView) scrollItem.findViewById(R.id.iv_scroll_show);
                    ImageOptions mOptions = new ImageOptions.Builder().build();
                    x.image().bind(imageViewShow, url, mOptions);
                    final int finalI = i;
                    imageViewShow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String path = topics.get(finalI).getUrl();
                            Intent intent = new Intent(getActivity(), BeautyWebViewActivity.class);
                            intent.putExtra("url", path);
                            startActivity(intent);
                        }
                    });
                    mLayout.addView(scrollItem);
                }
                List<BeautyPagerBean.ObjBean.EffectsBean> effects = beautyPagerBean.getObj().getEffects();
                for (int i = 0; i < effects.size(); i++) {
                    String title = effects.get(i).getTitle();
                    if (i < 4) {
                        Button codeBtn = new Button(getActivity());
                        setBtnAttribute(codeBtn, title, i);
                        mBtnListLayout1.addView(codeBtn);
                    } else {
                        Button codeBtn = new Button(getActivity());
                        setBtnAttribute(codeBtn, title, i);
                        mBtnListLayout2.addView(codeBtn);
                    }
                }
                List<BeautyPagerBean.ObjBean.HotWordsBean> hotWords = beautyPagerBean.getObj().getHotWords();
                for (int i = 0; i < 3; i++) {
                    String title = hotWords.get(i).getTitle();
                    Button codeBtn = new Button(getActivity());
                    setBtnAttribute(codeBtn, title, i);
                    codeBtn.setTextColor(Color.RED);
                    mBtnListLayout3.addView(codeBtn);

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
        x.http().get(new RequestParams(NetConfig.BEAUTYBUY_YOULIKE), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                BeautyYouLikeBean beautyYouLikeBean = gson.fromJson(result, BeautyYouLikeBean.class);

                List<BeautyYouLikeBean.ObjBean.ListDataBean> listData = beautyYouLikeBean.getObj().getListData();
                for (int i = 0; i < listData.size(); i++) {
                    youLike.add(listData.get(i));
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
        x.http().get(new RequestParams(NetConfig.BEAUTYBUY_LOCAL), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                BeautyLocalBean beautyLocalBean = gson.fromJson(result, BeautyLocalBean.class);
                List<BeautyLocalBean.ObjBean.ListDataBean> listData = beautyLocalBean.getObj().getListData();
                for (int i = 0; i < listData.size(); i++) {
                    local.add(listData.get(i));
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void initView(View view) {
        mListView = (ListView) view.findViewById(R.id.lv_beatubuy_show);
        View headView = LayoutInflater.from(getActivity()).inflate(R.layout.head_beautybuy, null);
        mTextViewPop = (TextView) view.findViewById(R.id.tv_beautybuy_bar);
        mTextView = (TextView) headView.findViewById(R.id.tv_head_button);
        point_ll = (LinearLayout) headView.findViewById(R.id.point_ll);
        mBtnListLayout1 = (LinearLayout) headView.findViewById(R.id.ll_beauty_show1);
        mBtnListLayout2 = (LinearLayout) headView.findViewById(R.id.ll_beauty_show2);
        mBtnListLayout3 = (LinearLayout) headView.findViewById(R.id.ll_beauty_show3);
        mViewPager = (ViewPager) headView.findViewById(R.id.vp_beauty_show);
        mLayout = (LinearLayout) headView.findViewById(R.id.ll_beauty_scroll);
        mRecyclerView = (RecyclerView) headView.findViewById(R.id.rv_beauty_show);
        mLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mListView.addHeaderView(headView);

    }

    private void setBtnAttribute(Button codeBtn, String btnContent, int id) {
        if (null == codeBtn) {
            return;
        }
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        codeBtn.setBackgroundResource(R.drawable.shape);
        codeBtn.setTextColor(Color.BLACK);
        codeBtn.setTextSize(15);
        codeBtn.setId(id);
        codeBtn.setText(btnContent);
        codeBtn.setWidth(dm.widthPixels / 4);
        codeBtn.setHeight(10);
    }

    private void showMainMenu(final View view) {

        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.view_pop_menu, null);

        final ListView mainMeneLV = (ListView) contentView.findViewById(R.id.menu_listview);
        ArrayAdapter<String> mainMenuAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, mainMenuItems);

        mainMeneLV.setAdapter(mainMenuAdapter);


        final ListView subMeneLV = (ListView) contentView.findViewById(R.id.submenu_listview);
        final ArrayAdapter<String> subMenuAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, subMenueList);
        subMeneLV.setAdapter(subMenuAdapter);

        mainMeneLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    subMeneLV.setVisibility(View.INVISIBLE);
                } else {

                    subMeneLV.setVisibility(View.VISIBLE);
                    subMenueList.clear();
                    for (int i = 0; i < mainMenuItems.size(); i++) {
                        mainMeneLV.getChildAt(i).setBackgroundColor(Color.GRAY);
                    }
                    mainMeneLV.getChildAt(position).setBackgroundColor(Color.WHITE);
                    int lenth = sub_main_menuArr[position - 1].length;
                    for (int i = 0; i < lenth; i++) {
                        subMenueList.add(sub_main_menuArr[position - 1][i]);

                    }
                    subMenuAdapter.notifyDataSetChanged();
                }
            }
        });

        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        subMeneLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getActivity(), "您选择了"+ subMenueList.get(position), Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });

        popupWindow.showAsDropDown(view);

    }
}
